<template>
  <el-card class="article-card" shadow="hover">
    <template #header>
      <div class="card-header">
        <h1 class="article-title">{{ article.title }}</h1>
        <span class="article-author">作者: {{ article.author }}</span>
        <!-- 新增点赞数、收藏数和评论数显示，添加点击事件 -->
        <div class="header-stats">
          <span class="stat-item" @click.stop="handleLike">
            <el-icon :style="{ color: isLiked ? 'red' : '' }" class="btn-icon">
              <Check />
            </el-icon> {{ article.likedAmounts || 0 }}
          </span>
          <span class="stat-item" @click.stop="handleCollect">
            <el-icon :style="{ color: isCollected ? 'red' : '' }" class="btn-icon">
              <Star />
            </el-icon> {{ article.collectedAmounts || 0 }}
          </span>
          <span class="stat-item" @click.stop="handleComment">
            <el-icon class="btn-icon">
              <ChatLineRound />
            </el-icon> {{ article.commentedAmounts || 0 }}
          </span>
        </div>
      </div>
    </template>
    <div class="article-info">
      <div class="info-item">
        <el-card class="description-card" shadow="hover">
          {{ article.introduction }}
        </el-card>
      </div>
      <div>
        <span class="label">更新时间:</span>
        <span class="value">{{ article.updateTime }}</span>
      </div>
      <!-- 添加默认插槽 -->
      <div class="info-item">
        <slot></slot>
      </div>
    </div>
  </el-card>

  <!-- 楼评论 -->
  <el-dialog v-model="dialogVisible" title="评论详情" width="60%">
    <el-scrollbar height="500px">
      <!-- 评论列表 -->
      <div class="comment-list">
        <CommentItem v-for="comment in comments" :key="comment.id" :comment="comment" :avatar="comment.userAvatar"
          :name="comment.userNickname" @view-floor="handleReply(comment)" />
      </div>
    </el-scrollbar>

    <!-- 评论输入框 -->
    <div class="comment-input">
      <el-input v-model="commentText" type="textarea" :rows="3" :placeholder="replyPlaceholder" />
      <div class="input-footer">
        <el-button type="primary" @click="handleCommentSubmit" :loading="commentLoading">
          提交评论
        </el-button>
      </div>
    </div>
  </el-dialog>

  <!--层评论-->
  <el-dialog v-model="dialogVisibleFloor" title="评论详情" width="60%">
    <div class="comment-item-main">
      <div class="comment-header">
        <el-avatar :src="currentHouse.userAvatar" />
        <span class="author">{{ currentHouse.userNickname }}</span>
        <span class="time">{{ formatTime(currentHouse.createTime) }}</span>
      </div>
      <div class="comment-content">{{ currentHouse.content }}</div>

      <!-- 回复按钮和子评论 -->
      <div class="comment-actions">
        <!-- <el-button size="small" @click="$emit('reply', comment)">回复</el-button> -->
        <el-button size="small">共{{ currentHouse.floorAmount }}条回复</el-button>
      </div>
    </div>
    <el-scrollbar height="500px">
      <!-- 评论列表 -->
      <div class="comment-list">
        <CommentItemFloor v-for="comment in commentsFloor" :key="comment.commentId" :comment="comment" :avatar="comment.userAvatar"
          :name="comment.userNickname" @view-floor="handleReplyFloor" @reply="handleReplytoFloor" />
      </div>
    </el-scrollbar>

    <!-- 评论输入框 -->
    <div class="comment-input">
      <el-input v-model="commentTextFloor" type="textarea" :rows="3" :placeholder="replyPlaceholderFloor" />
      <div class="input-footer">
        <el-button @click="cancelReplyFloor">取消回复</el-button>
        <el-button type="primary" @click="handleCommentSubmitFloor" :loading="commentLoadingFloor">
          提交评论
        </el-button>
      </div>
    </div>
  </el-dialog>

</template>

<script setup>
import { defineProps, ref, watch } from 'vue';
// 引入需要的图标
import { Check, Star, ChatLineRound } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import require from '../require';
import FloorComments from './FloorComments.vue';
import CommentItemFloor from './CommentItemFloor.vue';

// 在原有响应式变量后添加
const floorComments = ref({}); // 存储楼层评论 {[commentId]: []}
const currentHouse = ref(null); // 当前展开的楼评论

const formatTime = (time) => {
  return new Date(time).toLocaleString();
};

const props = defineProps({
  article: {
    type: Object,
    required: true,
    default: () => ({
      articleId: '',
      author: '',
      title: '',
      introduction: '',
      updateTime: '',
      likedAmounts: 0,
      collectedAmounts: 0,
      commentedAmounts: 0,
      currentUserCollect: false,
      currentUserLike: false,
    })
  }
});

// 使用 ref 包裹 article 以实现响应式更新
const article = ref({ ...props.article });

// 添加点击状态
const isLiked = ref(props.article.currentUserLike || false);
const isCollected = ref(props.article.currentUserCollect || false);
const isCommented = ref(false);

// 监听 props.article 变化
watch(() => props.article, (newArticle) => {
  article.value = { ...newArticle };
  isLiked.value = newArticle.currentUserLike || false;
  isCollected.value = newArticle.currentUserCollect || false;
}, { deep: true });

// 处理点赞事件
const handleLike = async () => {
  try {
    // 临时保存当前状态
    const tempLikedAmounts = article.value.likedAmounts + (isLiked.value ? -1 : 1);
    const tempIsLiked = !isLiked.value;

    // 先更新本地状态
    article.value.likedAmounts = tempLikedAmounts;
    isLiked.value = tempIsLiked;

    const res =  await require.post('/user/likeArticle', {
      articleId: article.value.articleId
    });
    ElMessage.success(isLiked.value ? '点赞成功' : '取消点赞成功');
  } catch (error) {
    // 请求失败，回滚状态
    article.value.likedAmounts = article.value.likedAmounts + (isLiked.value ? 1 : -1);
    isLiked.value = !isLiked.value;
    ElMessage.error(isLiked.value ? '取消点赞操作失败' : '点赞操作失败');
  }
};

// 处理收藏事件
const handleCollect = async () => {
  try {
    // 临时保存当前状态
    const tempCollectedAmounts = article.value.collectedAmounts + (isCollected.value ? -1 : 1);
    const tempIsCollected = !isCollected.value;

    // 先更新本地状态
    article.value.collectedAmounts = tempCollectedAmounts;
    isCollected.value = tempIsCollected;

    await require.post('/user/collectArticle', {
      articleId: article.value.articleId,
    });
    ElMessage.success(isCollected.value ? '收藏成功' : '取消收藏成功');
  } catch (error) {
    // 请求失败，回滚状态
    article.value.collectedAmounts = article.value.collectedAmounts + (isCollected.value ? 1 : -1);
    isCollected.value = !isCollected.value;
    ElMessage.error(isCollected.value ? '取消收藏操作失败' : '收藏操作失败');
  }
};

// 处理评论事件
// 添加必要的响应式变量
const dialogVisible = ref(false);
const commentText = ref('');
const commentLoading = ref(false);
const comments = ref([]);

// 修改评论获取逻辑
const handleComment = async () => {
  try {
    const res = await require.post('user/getArticleCommentList', {
        articleId: article.value.articleId,
        start: 0,      // 根据分页需求调整
        size: 1000       // 根据分页需求调整
    });
    
    // 更新数据结构匹配后端响应
    comments.value = res.commentList;
    article.value.commentedAmounts = res.commentAmount;
    
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '加载评论失败');
  }
};

// 修改评论提交部分
const handleCommentSubmit = async () => {
  try {
    commentLoading.value = true;
    const res = await require.post('/user/commentToArticle', {  // 根据实际提交接口修改
      articleId: article.value.articleId,
      content: commentText.value.trim(),
    });

    // 更新本地数据（根据实际返回数据结构调整）
    const newComment = res.comment

    comments.value = [newComment, ...comments.value];
    
    // 更新评论数
    article.value.commentedAmounts += 1;

    // 重置状态
    commentText.value = '';
    //currentReply.value = null;
    replyPlaceholder.value = '请输入您的评论';
  } finally {
    commentLoading.value = false;
  }
};

// 取消回复
const cancelReplyFloor = () => {
  cancelReplyFloor.value = null;
  replyPlaceholderFloor.value = '请输入你的评论';
};

//const currentReply = ref(null);
const replyPlaceholder = ref('请输入你的评论');



const dialogVisibleFloor = ref(false);
const commentTextFloor = ref('');
const commentLoadingFloor = ref(false);
const commentsFloor = ref([]);
const replyPlaceholderFloor = ref('请输入你的回复');
const currentReplyFloor = ref(null);

const handleReply = async (comment) => {
  console.log(comment);
  currentHouse.value = comment; // 记录当前楼层ID
  dialogVisibleFloor.value = true; // 打开楼层评论弹窗
  const res = await require.post('user/getFloorCommentList', {
    commentId: comment.commentId,
    start: 0,      // 根据分页需求调整
    size: 1000       // 根据分页需求调整
  });
  commentsFloor.value = res.commentList; // 更新楼层评论列表
};


const handleReplyFloor = async (comment) => {
  try {
    const res = await require.post('user/getArticleCommentList', {
      articleId: article.value.articleId,
      start: 0,      // 根据分页需求调整
      size: 1000       // 根据分页需求调整
    });

    // 更新数据结构匹配后端响应
    comments.value = res.commentList;
    article.value.commentedAmounts = res.commentAmount;

    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '加载评论失败');
  }
  
  replyPlaceholder.value = `回复 @${comment.userNickname}: `;
}

const handleReplytoFloor = (comment) => {
  currentReplyFloor.value = comment;
  replyPlaceholderFloor.value = `回复 @${comment.userNickname}: `;
}

const handleCommentSubmitFloor = async () => {
  if (!currentReplyFloor.value) {
    try {
      commentLoadingFloor.value = true;
      const res = await require.post('/user/replyCommentHouse', {  // 根据实际提交接口修改
        commentId: currentHouse.value.commentId,
        content: commentTextFloor.value.trim()
      });

      // 更新本地数据（根据实际返回数据结构调整）
      const newComment = res.comment

      commentsFloor.value = [newComment, ...commentsFloor.value];

      // 更新楼层评论数
      currentHouse.value.floorAmount += 1;
      article.value.commentedAmounts += 1;

      // 重置状态
      commentTextFloor.value = '';
      currentReplyFloor.value = null;
      replyPlaceholderFloor.value = '请输入你的回复';
    } finally {
      commentLoadingFloor.value = false;
    }
  } else {
    try {
      commentLoadingFloor.value = true;
      const res = await require.post('/user/replyCommentFloor', {  // 根据实际提交接口修改
        commentId: currentReplyFloor.value.commentId,
        content: commentTextFloor.value.trim()
      });

      // 更新本地数据（根据实际返回数据结构调整）
      const newComment = res.comment

      commentsFloor.value = [newComment, ...commentsFloor.value];

      // 更新楼层评论数
      currentHouse.value.floorAmount += 1;
      article.value.commentedAmounts += 1;

      // 重置状态
      commentTextFloor.value = '';
      currentReplyFloor.value = null;
      replyPlaceholderFloor.value = '请输入你的回复';
    } finally {
      commentLoadingFloor.value = false;
    }
  }

  
};

</script>

<style scoped>
.comment-list {
  padding: 10px;
}

.comment-input {
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.input-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  gap: 10px;
}

:deep(.el-dialog__body) {
  padding: 15px 20px;
}
.article-card {
  margin-bottom: 20px;
  transition: box-shadow 0.3s;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.article-title {
  font-size: 18px;
  font-weight: bold;
}

.article-info {
  display: flex;
  flex-direction: column;
}

.info-item {
  display: flex;
  margin-top: 12px;
  margin-bottom: 12px;
  align-items: center;
}

.label {
  font-weight: bold;
  margin-right: 10px;
  text-align: right;
  color: #606266;
}

.value {
  flex: 1;
  word-break: break-word;
  color: #303133;
}

/* 调整描述框样式 */
.description-card {
  flex: 1;
  margin-left: 10px;
  padding: 5px;
  text-indent: 2em; 
  line-height: 1.6; 
  font-size: 14px; 
  word-wrap: break-word; 
  word-break: normal; 
  white-space: normal; 
  text-align: left; 
}

/* 新增统计信息样式 */
.header-stats {
  display: flex;
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: #606266;
}

.btn-icon{
  font-size: 30px;
}

.comment-item {
  padding: 10px;
  margin: 10px 0;
  border-radius: 4px;
  background: #f8f9fa;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  margin-bottom: 5px;
}

.author {
  font-weight: 500;
}

.time {
  font-size: 0.9em;
  color: #999;
}

.comment-content {
  margin-left: 28px;
}

.replies {
  margin-left: 30px;
  border-left: 2px solid #eee;
  padding-left: 15px;
}

.comment-actions {
  margin-top: 8px;
  margin-left: 28px;
}

.comment-item-main{
  padding: 10px;
    margin: 10px 0;
    border-radius: 4px;
    background: #c8d5e1;
}
</style>